package cn.com.klun.tjy.other.zkUsed;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Date;

public class AdminClient implements Watcher {
    private Logger logger = LoggerFactory.getLogger(AdminClient.class);
    ZooKeeper zk;
    String hostPort;

    public AdminClient(String hostPort) {
        this.hostPort = hostPort;
    }
    void start() throws IOException {
        zk = new ZooKeeper(hostPort,15000,this);
    }
    void stopZK() throws InterruptedException {
        zk.close();
    }
    void listState() throws KeeperException, InterruptedException {
        try{
            Stat stat = new Stat();
            byte masterData[] = zk.getData("/master",false,stat);
            Date startDate = new Date(stat.getCtime()); //此处放入时间的作用
            logger.info("master:" +new String(masterData)+"since"+startDate);
        } catch (KeeperException.NoNodeException e){
            logger.info("no master");
        }
        logger.info("worker:");
        for(String w :zk.getChildren("/workers",false)){
            byte data[] = zk.getData("/workers/"+w,false,null);
            String state =  new String(data);
            logger.info("&&&&&&&&&/t"+w+":" + state);
        }
        logger.info("Tasks:");
        for(String t : zk.getChildren("/assign",false)){
            logger.info("%%%%%%%%%%/t"+t);
        }
    }
    @Override
    public void process(WatchedEvent watchedEvent) {
        logger.info(watchedEvent+"");
    }

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        AdminClient c = new AdminClient("192.168.137.12:2181");
        c.start();
        c.listState();
        Thread.sleep(3330333);
        c.stopZK();
    }
}
